package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author by 孙有泽
 * @Date 2025/3/23 21:05
 * @Description
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShopCartMapper shopCartMapper;

    @Autowired
    private OrderDatailsMapper orderDatailsMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Override
    public OrderSubmitVO sumbit(OrdersSubmitDTO orderSubmitDto) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDto,orders);
        orders.setNumber(System.currentTimeMillis()+"");//订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        AddressBook byId = addressBookMapper.getById(orderSubmitDto.getAddressBookId());
        if(byId == null){
            throw  new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        orders.setPhone(byId.getPhone());
        orders.setAddress(byId.getDetail());
        orders.setConsignee(byId.getConsignee());
        User user = userMapper.selectById(BaseContext.getCurrentId());
        if(user == null){
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setUserName(user.getName());
        orderMapper.insert(orders);
        List<OrderDetail> orderDetails = new ArrayList<>();
        List<ShoppingCart> shoppingCarts=shopCartMapper.list(BaseContext.getCurrentId());
        if (shoppingCarts == null || shoppingCarts.size() == 0){
            throw  new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail,"id");
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        orderDatailsMapper.insertBatch(orderDetails);
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shopCartMapper.clean(shoppingCart);
        return OrderSubmitVO.builder().id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
/*        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;*/
        //模拟支付成功 修改订单转态
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }
    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }
}
